﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Collections;

namespace FixEngine
{
    public class FieldFactory
    {
        private FieldFactory()
        { 
        }
        static Dictionary<string,Type> _table = null;
        static FieldFactory()
        {
            if (_table == null)
            {
                _table = new Dictionary<string, Type>();
                Type[] types = Assembly.GetExecutingAssembly().GetTypes();
                foreach (Type type in types)
                {
                    Type iField = type.GetInterface(typeof(IField).FullName, true);
                    if (iField != null)
                    {
                        if (type.IsAbstract||type.IsInterface)
                            continue;

                        IField instance=(IField)Activator.CreateInstance(type);
                        string key = string.Format("{0}{1}", instance.Version, instance.TagID);
                        if (!_table.ContainsKey(key))
                        {
                            _table.Add(key, type);    
                        }
                    }
                }
            }
        }
        public static IField CreateField(FixVersion ver,int tagid, string value)
        {
            string key = string.Format("{0}{1}", ver.ToString(), tagid);
            Type type = _table[key];
            IField newInstance=(IField)Activator.CreateInstance(type);
            newInstance.Value = value;
            return newInstance;
        }
        public static IField CreateField(FixVersion ver, int tagid)
        {
            string key = string.Format("{0}{1}", ver.ToString(), tagid);
            Type type = _table[key];
            IField newInstance = (IField)Activator.CreateInstance(type);
            return newInstance;
        }
    }
}
